<template>
  <div class="cart-container">
    <div class="page-header">
      <h2>我的购物车</h2>
    </div>

    <el-card v-if="cartItems.length > 0">
      <el-table
        v-loading="isLoading"
        :data="cartItems"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="商品ID" width="80" />
        <el-table-column label="商品信息" width="300">
          <template #default="scope">
            <div class="product-info">
              <img :src="scope.row.image" alt="商品图片" class="product-image">
              <div class="product-details">
                <div class="product-title">{{ scope.row.title }}</div>
                <div class="product-category">{{ scope.row.categoryName }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="单价" width="120">
          <template #default="scope">
            <span class="price">¥{{ scope.row.price.toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="数量" width="180">
          <template #default="scope">
            <el-input-number
              v-model="scope.row.quantity"
              :min="1"
              :max="99"
              @change="handleQuantityChange(scope.row)"
              size="small"
            />
          </template>
        </el-table-column>
        <el-table-column label="小计" width="120">
          <template #default="scope">
            <span class="subtotal">¥{{ (scope.row.price * scope.row.quantity).toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100">
          <template #default="scope">
            <el-button type="danger" text @click="removeFromCart(scope.row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="cart-footer">
        <div class="select-all">
          <el-checkbox v-model="selectAll" @change="handleSelectAll">全选</el-checkbox>
        </div>
        <div class="cart-summary">
          <div class="summary-text">
            已选 {{ selectedCount }} 件商品，合计：
          </div>
          <div class="total-price">
            ¥{{ totalPrice.toFixed(2) }}
          </div>
          <el-button type="primary" size="large" @click="goToCheckout" :disabled="selectedCount === 0">
            结算
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 空购物车状态 -->
    <div v-else class="empty-cart">
      <el-empty description="购物车是空的">
        <template #image>
          <el-icon><i-ep-shopping-cart /></el-icon>
        </template>
        <el-button type="primary" @click="goToProducts">去购物</el-button>
      </el-empty>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useCartStore } from '../../store'

const router = useRouter()
const cartStore = useCartStore()
const isLoading = ref(false)
const selectAll = ref(false)
const selectedItems = ref([])

// 从购物车store获取商品
const cartItems = computed(() => cartStore.items)

// 计算总价
const totalPrice = computed(() => {
  if (selectedItems.value.length > 0) {
    return selectedItems.value.reduce((total, item) => total + item.price * item.quantity, 0)
  }
  return cartStore.totalPrice
})

// 计算已选数量
const selectedCount = computed(() => {
  return selectedItems.value.reduce((count, item) => count + item.quantity, 0)
})

onMounted(() => {
  // 初始全选
  selectAll.value = cartItems.value.length > 0
  if (selectAll.value) {
    selectedItems.value = [...cartItems.value]
  }
})

const handleSelectionChange = (selection) => {
  selectedItems.value = selection
  selectAll.value = selection.length === cartItems.value.length && cartItems.value.length > 0
}

const handleSelectAll = (value) => {
  selectAll.value = value
  if (value) {
    selectedItems.value = [...cartItems.value]
  } else {
    selectedItems.value = []
  }
}

const handleQuantityChange = (item) => {
  cartStore.updateQuantity(item.id, item.quantity)
  ElMessage.success('数量已更新')
}

const removeFromCart = async (productId) => {
  try {
    cartStore.removeFromCart(productId)
    // 更新选中的商品列表
    selectedItems.value = selectedItems.value.filter(item => item.id !== productId)
    // 检查是否需要更新全选状态
    selectAll.value = selectedItems.value.length === cartItems.value.length && cartItems.value.length > 0
    ElMessage.success('商品已从购物车移除')
  } catch (error) {
    ElMessage.error('移除失败，请稍后重试')
  }
}

const goToCheckout = () => {
  if (selectedItems.value.length === 0) {
    ElMessage.warning('请选择要结算的商品')
    return
  }
  
  // 将选中的商品保存到sessionStorage，方便结算页面使用
  sessionStorage.setItem('checkoutItems', JSON.stringify(selectedItems.value))
  router.push('/order/confirm')
}

const goToProducts = () => {
  router.push('/products')
}
</script>

<style scoped>
.cart-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 30px;
}

.page-header h2 {
  font-size: 24px;
  color: #333;
}

.product-info {
  display: flex;
  align-items: center;
}

.product-image {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
  margin-right: 15px;
}

.product-details {
  flex: 1;
}

.product-title {
  font-size: 14px;
  margin-bottom: 5px;
  color: #333;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.product-category {
  font-size: 12px;
  color: #999;
}

.price,
.subtotal {
  color: #ff4d4f;
  font-weight: bold;
}

.subtotal {
  font-size: 16px;
}

.cart-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #e0e0e0;
}

.select-all {
  font-size: 14px;
}

.cart-summary {
  display: flex;
  align-items: center;
  gap: 20px;
}

.summary-text {
  font-size: 16px;
}

.total-price {
  font-size: 24px;
  font-weight: bold;
  color: #ff4d4f;
}

.empty-cart {
  padding: 60px 0;
  text-align: center;
}

.empty-cart .el-icon {
  font-size: 100px;
  color: #e0e0e0;
}

@media (max-width: 768px) {
  .cart-footer {
    flex-direction: column;
    align-items: stretch;
    gap: 20px;
  }
  
  .cart-summary {
    justify-content: flex-end;
  }
  
  .product-info {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .product-image {
    margin-right: 0;
  }
}
</style>